package {
	import UIAway.uif_view;
	
	import UIFree.ObjectEvent;
	import UIFree.uif_Timer;
	import UIFree.uif_app;
	import UIFree.uif_styles;
	
	import UIUtils.uif_JSONLoader;
	import UIUtils.uif_util;
	
	import away3d.cameras.lenses.PerspectiveLens;
	import away3d.containers.ObjectContainer3D;
	import away3d.core.base.SubGeometry;
	import away3d.entities.Mesh;
	import away3d.events.Stage3DEvent;
	import away3d.extrusions.PathExtrude;
	import away3d.extrusions.utils.Path;
	import away3d.loaders.Loader3D;
	import away3d.materials.BitmapMaterial;
	import away3d.materials.ColorMaterial;
	import away3d.materials.DefaultMaterialBase;
	import away3d.materials.methods.BasicDiffuseMethod;
	import away3d.materials.methods.FogMethod;
	import away3d.primitives.Cube;
	import away3d.primitives.Sphere;
	import away3d.primitives.WireframeCube;
	import away3d.tools.utils.Ray;
	import away3d.vf.HoverDragController;
	import away3d.vf.managers.awayLoadSection;
	import away3d.vf.meshUtils;
	import away3d.vf.vf_objectContainer3D;
	
	import com.adobe.net.URI;
	
	import descentFly.app.df_baseApp;
	import descentFly.app.df_events;
	import descentFly.app.df_managePanel;
	import descentFly.app.df_miniInterface;
	import descentFly.app.df_panel;
	import descentFly.app.df_styles;
	import descentFly.app.df_topTollbar;
	import descentFly.app.df_userInterface;
	import descentFly.away3D4.Background.df_bgSky;
	import descentFly.away3D4.Background.df_bgSpace;
	import descentFly.away3D4.Generator.df_monsterGenerator;
	import descentFly.away3D4.action.df_action;
	import descentFly.away3D4.action.df_actionRotate;
	import descentFly.away3D4.action.df_dir;
	import descentFly.away3D4.action.df_moving;
	import descentFly.away3D4.chips.df_chip3DS;
	import descentFly.away3D4.chips.df_chipAway;
	import descentFly.away3D4.chips.df_chipDummy;
	import descentFly.away3D4.chips.df_chipModel;
	import descentFly.away3D4.chips.df_monster;
	import descentFly.away3D4.controller.df_doorAway;
	import descentFly.away3D4.controller.df_robot;
	import descentFly.away3D4.controller.df_robotAway;
	import descentFly.away3D4.df_awaySpace;
	import descentFly.away3D4.df_loadSection;
	import descentFly.away3D4.doors.df_door;
	import descentFly.away3D4.doors.df_door3DS;
	import descentFly.away3D4.doors.df_rotateDoor;
	import descentFly.away3D4.exits.df_baseExit;
	import descentFly.controller.FlyController;
	import descentFly.controller.df_robotController;
	import descentFly.controller.df_userController;
	import descentFly.controller.myFlyController;
	import descentFly.data.df_classes;
	import descentFly.data.df_smallLevels;
	import descentFly.df_FData;
	import descentFly.df_optionsObject;
	import descentFly.df_player;
	import descentFly.df_space;
	import descentFly.df_utils;
	import descentFly.server.df_servers;
	import descentFly.server.mySocket;
	import descentFly.server.myserver;
	import descentFly.sound.df_soundManager;
	import descentFly.view.df_view;
	
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.display.StageDisplayState;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.external.ExternalInterface;
	import flash.geom.Matrix;
	import flash.geom.Matrix3D;
	import flash.geom.Rectangle;
	import flash.geom.Vector3D;
	import flash.system.Security;
	
	import jiglib.collision.CollDetectInfo;
	import jiglib.collision.CollDetectSphereBox;
	import jiglib.collision.CollisionInfo;
	import jiglib.debug.Stats;
	import jiglib.geometry.JBox;
	import jiglib.geometry.JSphere;
	import jiglib.geometry.JTriangleMesh;
	import jiglib.math.JMatrix3D;
	import jiglib.math.JNumber3D;
	import jiglib.physics.RigidBody;
	import jiglib.plugin.away3d4.Away3D4Mesh;
	import jiglib.plugin.away3d4.Away3D4Physics;
	
	import jiglib_vf.JVBox;
	import jiglib_vf.JVSphere;
	
	import space.sp_utils;
	
	[SWF(frameRate="60", backgroundColor="#000")]
	public class away_jiglib extends df_baseApp {
		
//		df_servers.DATA_URL = 'http://62.76.176.102/fly/data/';
		
		private var _view			: df_view;
		private var _space			: df_awaySpace;
		private var _myserver		: myserver;
		private var _externalData	: Object;
		private var _edParser		: df_FData;
		
		public function away_jiglib() {
			var i:int;
			Security.loadPolicyFile('xmlsocket://vmaya.ru:843');
			Security.allowDomain('*');
			super(new df_styles());
			
			var files: Array;
			if (params.data) files = params.data.split(',');
			
			if (files && files.length) 
				loadExternalData(files);
			else myServerInitialize();
		}
		
		protected function loadExternalData(files: Array): void {
			var i:int;
			if (params.debug)
				for (i=0; i<files.length; i++) files[i] = files[i] + '?' + Math.random();
			
			df_loadSection.loadJSONData(files, function(externalData: Array): void {
				myServerInitialize();
				
				_edParser = new df_FData();
				externalData.forEach(function(data: uif_JSONLoader, i: int, arr: Array): void {
					var dataObj: Object = _edParser.parseFDObject(data.jsonData, df_classes, df_smallLevels, df_servers.CLASSES_URL);
					if (_externalData && dataObj.levels) {
						for (i=0; i<dataObj.levels.length; i++) {
							var uri: URI = new URI( data.sourceURL);
							dataObj.levels[i].urlPattern = data.sourceURL.replace(uri.getFilename(), '%s');
						}
						_externalData.levels = _externalData.levels.concat(dataObj.levels);
						delete(dataObj.levels);
					}
					_externalData = uif_util.union(_externalData, dataObj);
				});
			});
		}
		
		protected function myServerInitialize(): void {
			_myserver = new myserver(This, params.model);
			_myserver.startUser(params.uid, params, doStartUser);
		}
		
		public function get view(): df_view {
			return _view;
		}
		
		override public function getInner(incx:Number=0, incy:Number=0, incw:Number=0, inch:Number=0):Rectangle {
			var rect: Rectangle = super.getInner();
			rect.inflate(0, ((viewHeight + df_topTollbar.HEIGHT) - params.height) / 2);
			return rect;
		}
		
		public function get viewHeight(): int {
			var viewHeight: int = df_view.MAXHEIGHT;
			if (viewHeight + df_topTollbar.HEIGHT > params.height)
				viewHeight = params.height - df_topTollbar.HEIGHT;
			return viewHeight;
		}
		
		override protected function createSpace(): df_space {
			var rect: Rectangle = getInner();
			rect.top += df_topTollbar.HEIGHT;
			_view 	= new df_view(this, '', true, rect, 1);
			_space 	= new df_awaySpace(_view, player, {
				fps				: 30,
				CAMBLAND		: 0.3,
				chipACCEL		: 1,
				chipTORMOS		: 0.25,
				chipMAXROLL		: 0.7,
				plockSupport	: int(params.plock) == 1
			});
			
			_space.levels = df_smallLevels.list;
			if (_externalData) 
				_space.levels = _space.levels.concat(_externalData.levels);
			
			return _space;
		}
		
		override protected function createSocial(): ISocial {
			return new df_defSocial(player.UID);
		}
		
		override protected function initialize(): void {
			super.initialize();
			
			var inner: Rectangle = getInner();
			new df_soundManager(_view.view);
			new df_userInterface(this, inner);
			
			
			var levelID: int = params.hasOwnProperty('level')?params.level:player.level;
			if (!levelID || (_space.levelIndexFromID(levelID) == -1)) 
				levelID = df_smallLevels.DEFAULTLEVELID;
			_space.levelID = levelID;
		}
		
		protected function doStartUser(data: Object): void {
			function doUpdateOptions(e: Event=null): void {
				if (player.UID) {
					ExternalInterface.call('CookieUID', player.UID);
				}
			}
			
			function completeED(e: Event=null): void {
				if (_edParser) _edParser.removeEventListener(Event.COMPLETE, completeED);
				if (_externalData) _externalData = _edParser.parseFDObject(_externalData, df_classes, _externalData, df_servers.CLASSES_URL);
				
				var user: Object = data.response[0];
				user = uif_util.union({
					avatar	: params.avatar,
					sex		: params.sex
				}, user);
				player	= new df_player(user, _myserver, stage);
				player.addEventListener(df_optionsObject.SETOPTIONS, doUpdateOptions);
				doUpdateOptions();
				/*
				_externalData.levels.forEach(function(level: Object, i: int, arr: Array): void {
				if (level.hasOwnProperty('Extends'))
				level.Extends.forEach(function(ext: Object, i: int, arr: Array): void {
				if (ext is  String) {
				if (_externalData.hasOwnProperty(ext))
				level.Extends[i] = _externalData[ext];
				else level.Extends[i] = df_smallLevels[ext];
				}
				});
				});*/
			}
			
			if (_edParser && !_edParser.loaded) _edParser.addEventListener(Event.COMPLETE, completeED);
			else completeED()
		}
	}
}